import wepy from 'wepy';

export default class Home extends wepy.mixin {
  data = {
    // 获取商品列表参数对象
    queryData: {
      query: '',
      cid: '',
      pagenum: 1,
      pagesize: 10,
    },
    // 商品列表
    goodsList: [],
    // 商品总条数
    total: 0,
    // 暂无图片
    none:
      'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3289561155,3667091394&fm=26&gp=0.jpg',
    // 判断是否在请求数据  起到节流效果
    isLoading: false,
    // 是否显示无数据了
    isover: true,
  };

  methods = {
    toGoodInfo(goods_id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + goods_id,
      });
    },
  };

  // 获取商品列表信息
  async getGoodsList(fn) {
    this.isLoading = true;
    const { data: res } = await wepy.get('/goods/search', this.queryData);
    if (res.meta.status !== 200) {
      fn && fn();
      return wepy.baseToast();
    }
    this.goodsList = this.goodsList.concat(res.message.goods);
    this.total = res.message.total;
    this.isLoading = false;
    // 短路运算符 fn存在调用 fn() 否则不调用
    fn && fn();
    this.$apply();
  }
  // 上拉加载更多触底
  onReachBottom() {
    if (this.isLoading) return;
    if (this.queryData.pagenum * this.queryData.pagesize > this.total) {
      return (this.isover = false);
    }
    this.queryData.pagenum++;
    this.getGoodsList();
  }
  // 监控上拉加载
  onLoad(options) {
    // 判断页面跳转 传递参数是 car_id 还是 query
    this.queryData.cid = options.cat_id ? options.cat_id : '';
    this.queryData.query = options.query ? options.query : '';
    this.getGoodsList();
  }
  onPullDownRefresh() {
    this.goodsList = [];
    this.queryData.pagenum = 1;
    this.isover = true;
    // 利用回调函数将 关闭下拉刷新函数传到请求数据里
    this.getGoodsList(() => {
      // 请求完数据关闭下拉刷新
      wepy.stopPullDownRefresh();
    });
  }
}
